import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import os


class my_email:
    # 发件人和收件人信息
    sender_email = "liangpc2@163.com"
    # receiver_email = "774329769@qq.com"
    # receiver_email = "229495590@qq.com"
    password = "ZYOZTDYGEXOKERIB"
    smtp_server = "smtp.163.com"
    smtp_port = 465

    def __init__(self,receiver_email:str) -> None:
        self.receiver_email = receiver_email

    def send_email(self, email_text: str, title: str, attach_dir=""):
        # 创建邮件
        message = MIMEMultipart()
        message["From"] = self.sender_email
        message["To"] = self.receiver_email
        message["Subject"] = title

        # 添加文本内容
        message.attach(MIMEText(email_text, "plain"))

        # 添加图片
        if os.path.isfile(attach_dir):
            with open(attach_dir, "rb") as image_file:
                image = MIMEImage(image_file.read(), name="image.png")
                message.attach(image)
        else:
            print(attach_dir+" 文件不存在")

        try:
            # 连接到SMTP服务器
            with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port) as server:
                # server.starttls() # 使用SSL时则要注销这行
                server.login(self.sender_email, self.password)
                server.sendmail(
                    self.sender_email, self.receiver_email, message.as_string()
                )

            print("邮件发送成功！")
        except:
            print("邮件发送失败")
            exit()
